﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using Telerik.Reporting.Expressions;

namespace ezCloud.Api.Common
{
    public static class Language
    {
        public static Dictionary<string,Dictionary<string,string>> languages = new Dictionary<string, Dictionary<string, string>>();
        [Function(Namespace="Language")]
        public static string Get(string language, string key)
        {
            //if (language == null) language = "vn"; 
            //if (!languages.ContainsKey(language))
            {
                languages[language] = getLanguage(language);
            }
            if (key == null) return "";
            return !languages[language].ContainsKey(key)? key : languages[language][key];
        }
        public static Dictionary<string,string> getLanguage(string language)
        {
            var result = new Dictionary<string, string>();
            /*HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost/api/Language/Get");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync("?lang=" + language).Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                return response.Content.ReadAsAsync<Dictionary<string, string>>().Result;
                
            }
            else
            {
                return null;
            }*/
            var context = new ezCloud.Data.ezCloudDataContext();
            var lang = context.Languages.Where(l => l.LanguageCode == language).First();
            var langValues = context.LanguageItemValues.Where(li => li.LanguageId == lang.LanguageId).Select(li => new { li.LanguageItemValue, li.LanguageItems.LanguageCode }).ToList();
            foreach(var ll in langValues)
            {
                result.Add(ll.LanguageCode, ll.LanguageItemValue);
            }
            return result;
        }
    }
}